﻿using CaseManagerLibrary.Auth;
using CaseManagerLibrary.Models;
using CaseManagerLibrary.Socket;
using PSDBurnService.Protocols;
using PSDDownloadService.SystemSettings;
using PSDLib.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PSDBurnService
{
    public class MessageManager
    {
        private BurnServiceContext context;
        public TcpManagerAsync tcpManager { get; set; }

        public bool Online { get; set; }

        public MessageManager(BurnServiceContext ctx)
        {
            Online = true;
            context = ctx;
        }

        public bool Init()
        {
            bool success = true;

            try
            {
                var ep = new IPEndPoint(IPAddress.Any, AppSettings.Setting.BurnListenPort);

                tcpManager = new TcpManagerAsync(ep);
                tcpManager.Received += TcpManager_Received;

                success = true;
            }
            catch (Exception ex)
            {
                success = false;
            }

            return success;
        }

        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="text"></param>
        /// <param name="remoteEp"></param>
        private void TcpManager_Received(string text, TcpClientState state)
        {
            try
            {
                MessageBase msg = MessageParser.Parse(text);

                if (msg != null)
                {
                    var processor = ClientMessageProcessor.Parse(msg);

                    processor?.Run(context, state);
                }
            }
            catch (Exception ex)
            {
                context.Logger.Error("处理消息失败：" + ex.Message + " " + text);
            }
        }

        public void Start()
        {
            if (tcpManager != null)
            {
                tcpManager.Start();

                context.Logger.Info("启动tcp消息服务");
            }
        }

        public void Stop()
        {
            if (tcpManager != null)
            {
                tcpManager.Stop();

                context.Logger.Info("停止tcp消息服务");
            }
        }

        public HResult Send(IPEndPoint ep, MessageBase message)
        {
            var result = tcpManager.Send(ep, message);

            if (!result.success)
            {
                Online = false;
                context.Logger.Error("发送消息失败：" + ep.ToString() + " " + result.message);
            }
            else
            {
                if (!Online)
                {
                    Online = true;
                    context.Logger.Info("消息服务恢复连接");
                }
            }

            return result;
        }

    }
}
